<template>
    <div class="buildingNode">
        <!--搜索条-->
        <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="是否强制节点：">
                <el-select v-model="isCompulsive">
                    <el-option label="全部" :value="undefined"></el-option>
                    <el-option label="是" value="1"></el-option>
                    <el-option label="否" value="0"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="节点名称：">
                <el-input v-model="nodeName"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="searchList" id="monitorEnter">查询</el-button>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="fn('add')">新建</el-button>
            </el-form-item>
        </el-form>

        <!--表格-->
        <el-table :data="tableData" border>
            <el-table-column type="index" label="序号" width="50"></el-table-column>
            <el-table-column prop="nodeName" label="节点名称" width="150"></el-table-column>
            <el-table-column prop="isCompulsive" label="是否强制" width="100">
                <template slot-scope="scope">
                    {{scope.row.isCompulsive == 1 ? '是' : '否'}}
                </template>
            </el-table-column>
            <el-table-column label="附件名称">
                <template slot-scope="scope">
                    <span v-for="(item,index) in scope.row.attachments">{{item.attachName}}<em v-show="index!=scope.row.attachments.length-1">,&nbsp;</em></span>
                </template>
            </el-table-column>
            <el-table-column prop="createTime" label="操作时间">
                <template slot-scope="scope">
                    {{scope.row.updateTime | getTimeString}}
                </template>
            </el-table-column>
            <el-table-column prop="createUserName" label="操作人"></el-table-column>
            <el-table-column prop="" label="操作">
                <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="fn('edit',scope.row)" :disabled="scope.row.nodeName=='回款'">编辑</el-button>
                    <!-- <el-button type="danger" size="mini" @click="fn('delete',scope.row)" :disabled="!scope.row.deletable || scope.row.devBanded">删除</el-button> -->
                    <el-button type="danger" size="mini" @click="fn('delete',scope.row)" :disabled="scope.row.nodeRuleNum == 0 ?false:true">删除</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="nodeRuleNum" label="关联节点规则">
                <template slot-scope="scope">
                    <span v-show="!scope.row.nodeRuleNum">{{scope.row.nodeRuleNum}}</span>
                    <el-button type="text" v-show="scope.row.nodeRuleNum" @click="searchBuilding(scope.row)">{{scope.row.nodeRuleNum}}</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagebar">
            <el-pagination
                    background
                    layout="total, sizes, prev, pager, next"
                    :current-page.sync="currentPage"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="pageSize"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :total="totalSize">
            </el-pagination>
        </div>

        <!--弹窗-->
        <el-dialog :title="editFlag?'编辑节点':'添加自定义节点'" :visible.sync="dialogVisible" width="600px">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" class="demo-ruleForm">
                <el-form-item label="节点名称：" prop="nodeName">
                    <el-input v-model="ruleForm.nodeName"
                              :disabled="editFlag"
                              style="width: 200px;" maxlength="15"></el-input>
                </el-form-item>
                <div class="hr"></div>
                <el-form-item label="是否可拆分：" prop="isDivisible">
                    <el-select v-model="ruleForm.isDivisible" style="width: 200px;" v-show="!editFlag">
                        <el-option label="是" :value="1"></el-option>
                        <el-option label="否" :value="0"></el-option>
                    </el-select>
                    <span v-show="editFlag">{{ruleForm.isDivisible?'是':'否'}}</span>
                </el-form-item>
                <el-form-item label="计算基数：" prop="calculationBaseNumber" v-if="ruleForm.isDivisible">
                    <el-select v-model="ruleForm.calculationBaseNumber" style="width: 200px;">
                        <el-option label="成交价" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="字段名称：" prop="customFieldName" v-if="ruleForm.isDivisible">
                    <el-input v-model="ruleForm.customFieldName"
                              style="width: 200px;" maxlength="10"></el-input>
                </el-form-item>
                <div class="hr"></div>
                <div v-for="(item,index) in ruleForm.attachments" :key="index">
                    <el-form-item label="附件名称：" :prop="'attachments.'+index+'.attachName'" 
                    :rules="{required:true,message:'请输入附件名称',trigger:'blur'}">
                        <el-input v-model="item.attachName" style="width: 200px;"
                                maxlength="15" :disabled="item.disabled==1"></el-input>
                        是否必填：
                        <el-select v-model="item.required" size="mini" style="width: 60px;">
                            <el-option label="是" :value="1"></el-option>
                            <el-option label="否" :value="0"></el-option>
                        </el-select>
                        <el-button size="mini" type="danger" @click="deleteNode(item)"
                                :disabled="item.disabled==1"
                                v-show="ruleForm.attachments.length>1">删除</el-button>
                    </el-form-item>
                </div>
                <el-form-item label="">
                    <el-button size="mini" type="primary" @click="addNode" v-show="ruleForm.attachments.length<4">添加附件名称</el-button>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>

export default {
    name:"buildingNode",
    created() {},
    mounted() {
        this.searchList()
        this.userName = localStorage.getItem('cmsUser')?JSON.parse(localStorage.getItem('cmsUser')).name:''
    },
    components: {},
    data() {
        return {
            nodeName: undefined,
            isCompulsive: undefined,
            tableData: [],
            currentPage: 1,
            pageSize: 10,
            totalSize: 0,

            //----------------
            dialogVisible: false,
            editFlag: false,
            ruleForm: {
                nodeName: '',
                isDivisible:'',
                calculationBaseNumber:1,
                customFieldName:'',
                attachments: [{required: 1}],
            },
            userName: '', // 系统登录的用户名字
            followTypeList: ['认购','签约','草签'],
            followTypeIdList: ['PURCHASE','SIGN','INITIAL'],
            rules: {
                nodeName: [
                    { required: true, message: '请输入节点名称', trigger: 'blur' },
                ],
                customFieldName: [
                    { required: true, message: '请输入字段名称', trigger: 'blur'}
                ],
                isDivisible: [
                    { required: true, message: '请选择是否可拆分', trigger: 'change'}
                ],
                calculationBaseNumber: [
                    { required: true, message: '请选择计算基数', trigger: 'change'}
                ],
            }
        }
    },
    methods: {
        // 查看楼盘
        searchBuilding(row){
            this.$router.push({path: '/pointRules',query: {nodeId:row.id, nodeName: row.nodeName}})
        },
        searchList () {
            let param = {}
            param.nodeName = this.nodeName
            param.isCompulsive = this.isCompulsive
            param.pageSize = this.pageSize
            param.pageNum = this.currentPage
            this.$axios.post('/estate/node/select', param).then(res => {
                this.totalSize = res.total
                this.tableData = res.nodes
                this.tableData.forEach(item=>{
                    if(!item.isDivisible){
                        item.isDivisible = 0
                    }
                })
            })
        },
        fn (type,row) {
            if (type == 'add') {
                this.dialogVisible = true
                this.editFlag = false
                this.ruleForm.id = undefined
                this.ruleForm.followType = 'CUSTOM'
                this.ruleForm.nodeName = ''
                this.ruleForm.isDivisible = 1
                this.ruleForm.calculationBaseNumber = 1
                this.ruleForm.customFieldName = ''
                this.ruleForm.attachments = [{required: 1}]
                this.isCompulsive = 0
            } else if (type == 'edit') {
                this.dialogVisible = true
                this.$nextTick(() => {
                    this.resetForm('ruleForm')
                    this.editFlag = true
                    this.ruleForm = JSON.parse(JSON.stringify(row))
                })
            } else if (type == 'delete') {
                this.$confirm('确定删除当前的'+row.nodeName+'?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post('/estate/node/delete', {id:row.id}).then(res => {
                        this.$message.success('删除成功')
                        this.searchList()
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        // 分页器改变页码
        handleCurrentChange () {
            this.searchList()
        },
        // 分页器改变每页条数
        handleSizeChange (val) {
            this.pageSize = val
            this.searchList()
        },
        /** 新增弹框 */
        addNode(){
            this.ruleForm.attachments.push({required: 1})
        },
        deleteNode(val){
            const index = this.ruleForm.attachments.indexOf(val)
            if (index > -1) {
                this.ruleForm.attachments.splice(index,1)
            }
        },
        submitForm(formName) {
            console.log(formName);
            
            this.$refs[formName].validate((valid) => {
                console.log(valid);
                
                if (valid) {
                    let param = {}
                    param.id = this.ruleForm.id
                    param.nodeName = this.ruleForm.nodeName
                    param.isDivisible = this.ruleForm.isDivisible
                    param.calculationBaseNumber = this.ruleForm.calculationBaseNumber
                    param.customFieldName = this.ruleForm.customFieldName
                    const index = this.followTypeList.indexOf(param.nodeName)
                    let followType
                    if (index > -1) {
                        followType = this.followTypeIdList[index]
                    } else {
                        followType = 'CUSTOM'
                    }
                    param.isCompulsive = this.ruleForm.isCompulsive?this.ruleForm.isCompulsive:0
                    param.followType = followType
                    param.createUserName = this.userName
                    param.attachments = []
                    let flag = true
                    this.ruleForm.attachments.forEach((item,index) => {
                        param.attachments.push({attachKey:index,attachName: item.attachName,required:item.required,disabled: item.disabled==1?1:0})
                    })
                    if (flag) {
                        console.log(param);
                        
                        this.$axios.post('/estate/node/addUpdate', param).then(res => {
                            this.$message.success(this.editFlag?'编辑成功':'新增成功')
                            this.searchList()
                        })
                        this.dialogVisible = false
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        }
    },
    computed: {},
    filters:{
        getTimeString (timestamp) {
            if (timestamp) {
                const time = new Date(timestamp)
                let dateStr = ''
                const year = time.getFullYear()
                const month = String(time.getMonth() + 1).length === 1 ? '0' + (time.getMonth() + 1) : (time.getMonth() + 1)
                const day = String(time.getDate()).length === 1 ? '0' + time.getDate() : time.getDate()
                dateStr = year + '-' + month + '-' + day
                let timeStr = ''
                const hours = time.getHours()
                const hh = String(hours).length === 1 ? '0' + hours : hours
                const minutes = time.getMinutes()
                const mm = String(minutes).length === 1 ? '0' + minutes : minutes
                const seconds = time.getSeconds()
                const ss = String(seconds).length === 1 ? '0' + seconds : seconds
                timeStr = hh +':'+mm+':'+ss
                return dateStr + ' ' + timeStr
            } else {
                return ''
            }
        },
    }
}
</script>
<style lang="stylus" scoped>
    .buildingNode {
        .hr{
            background-color:#DCDFE6;
            height :1px;
            margin :30px -20px 30px;
        }
    }
</style>